
package com.xinthe.krisco.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Sudarsan This Class is an Utility for Database
 *
 */
public class DatabaseUtil {

	private static Connection connection = getDatabaseProperties();

	private DatabaseUtil() {

	}

	/**
	 * @return This method is used to read all the database properties from the
	 *         file, which is available in <b>inputfiles</b> directory and
	 *         creates a JDBC <code>Connection</code> Object.
	 */
	private static Connection getDatabaseProperties() {
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(new File(
					"inputfiles/database.properties"));
			Properties properties = new Properties();
			properties.load(inputStream);

			connection = DriverManager.getConnection(
					properties.getProperty("oms.oracle.url"),
					properties.getProperty("oms.oracle.username"),
					properties.getProperty("oms.oracle.password"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			if(inputStream!=null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return connection;
	}

	/**
	 * @return a single instance of JDBC Connection to the caller of the method
	 */
	public static Connection getConnection() {
		return connection;
	}
	public static void cleanup(Connection con,PreparedStatement ps,ResultSet rs)
	{
		if(con!=null)
		{
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(ps!=null)
		{
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(rs!=null)
		{
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
